import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
const _axios = axios.create({
    baseURL: process.env.VUE_APP_BASE_API
})

_axios.interceptors.request.use(
    (config) => {
        if (store.state.user.token) {
            config.headers.Authorization = `Bearer ${store.state.user.token}`
        }
        return config
    },
    (error) => Promise.reject(error)
)
_axios.interceptors.response.use(
    (res) => {
        if (res.data.success) {
            return res.data
        } else {
            Message.error(res.data.message)
            return Promise.reject(res.data.message)
        }
    },
    (error) => {
        if (error.response && error.response.status === 401) {
            store.commit('user/logout')
            router.push('/login?topath=' + location.href.split('#')[1])
        }
        return Promise.reject(error)
    }
)
export default _axios